from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models.marketing import Deposit
from app.schemas.marketing import DepositCreate,DepositUpdate
from app.controllers.customer.users import users_controller

class DepositController(CRUDBase[Deposit, DepositCreate, DepositUpdate]):
    def __init__(self):
        super().__init__(model=Deposit)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict() for obj in objs]
        return total, data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self, obj_in: DepositCreate):
        if obj_in.price<=0:
            return True
        await self.create(obj_in=obj_in)
        deposit, created = await Deposit.get_or_create(order_goods_id=obj_in.order_goods_id,order_id=obj_in.order_id)
        if not created:
            # 如果对象已经存在，更新它
            deposit.price = obj_in.price
            await deposit.save()
        await users_controller.update_money(type=1,user_id=obj_in.user_id)
        return True

    async def do_update(self, obj_in: DepositUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        await users_controller.update_money(type=1, user_id=obj_in.user_id)
        return True

    async def do_delete(self, data_id: int):
        user_id = await self.model.filter(id=data_id).first().values("user_id")
        await self.remove(id=data_id)
        await users_controller.update_money(type=1, user_id=user_id['user_id'])
        return True



deposit_controller =DepositController()
